package com.hui.xiao.xiaohui.io;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.hui.xiao.xiaohui.R;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2016/6/4.
 */
public class SharePreferencesTest extends Activity {
    SharedPreferences preferences;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.share_preferences);
        preferences = getSharedPreferences("sqq", MODE_PRIVATE);
        editor = preferences.edit();
        Button write = (Button) findViewById(R.id.write);
        final Button read = (Button) findViewById(R.id.read);

        write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                editor.putString("time", sdf.format(new Date()));
                editor.putInt("random", (int) (Math.random() * 100));
                editor.commit();
            }
        });
        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String time = preferences.getString("time", null);
                int num = preferences.getInt("random", 0);
                String msg = time == null ? "未写入数据" : "写入时间:" + time + "\n写入随机数:" + num;
                Toast.makeText(SharePreferencesTest.this, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
